/**
 * 用户登录业务代码
 */


const db = require("../../db/db")
const initModel = require("../../models/init-models")
const {user} = initModel(db);
const axios = require("axios");
// 引入生成token中间件
let jwt = require('jsonwebtoken');

// appId
const appId = "wx9b8d3877e0eb41e3";
// appSecret
const appSecret = "cc4ee0e42ffbf424b1ca9bd5fea3fbf9";

module.exports = {
  // 微信授权
  weChatLogin: async (req, res) => {
    // 回调地址
    const redirect_url = encodeURIComponent("http://1.15.155.180:3000/api/admin");
    // 获取用户信息模式
    const scope = "snsapi_base"
    let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + redirect_url + '&response_type=code&scope=' + scope + '&state=123#wechat_redirect';

    // 返回授权地址
    res.send({
      status: 200,
      msg: "获取授权地址成功",
      data: {
        url
      }
    })
  },
  // 登录
  login: async (req, res) => {
    // 获取参数
    let {code} = req.body;
    // 判断是否传参
    if (code == null) {
      res.send({
        status: 400,
        msg: "缺少参数"
      });
      return;
    }

    // 获取用户openid
    let openidUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${code}&grant_type=authorization_code`
    let {data: result} = await axios.get(openidUrl);
    // 判断code的值是否有效
    if(Object.keys(result)[0] == "errcode") {
      // 返回报错信息
      res.send({
        result
      });
      return;
    }
    // 解构 result   openid
    let {openid} = result;
    // 拿openid去数据库查找是否存在
    let findOpenId = await user.findOne({
      where: {openid},
      attributes:{exclude: ['openid']} // 不返回openid给用户
    })
    if(findOpenId != null) {
      // 查到信息返回
      // 生成token
      let token = 'Bearer ' + jwt.sign(
          {name:findOpenId.user_name, id: findOpenId.id, superAdmin: true},
          'userToken',
          {expiresIn: '24h'}
      )
      res.send({
        status: 200,
        msg: "登录成功",
        data: findOpenId,
        token,
      });
      return;
    }
    // 数据库中没有该用户信息则请求获取用户信息

    // 获取全局 access_token
    let accessUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`
    let accessData = await axios.get(accessUrl);
    let {access_token} = accessData.data;
    // 请求用户信息
    let userUrl = `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${access_token}&openid=${openid}&lang=zh_CN`
    let {data: userInfo} = await axios.get(userUrl);
    if(userInfo.errcode == 40003 || userInfo.errcode == 40029) {
      // 返回报错的用户信息
      res.send({
        userInfo
      });
      return;
    }
    // 存储用户信息
    let createUser = await user.create({
      openid: userInfo.openid,
      headimgurl: userInfo.headimgurl,
      user_name: userInfo.nickname,
      sex: userInfo.sex,
      address: userInfo.city,
      create_time: new Date()
    })
    // 返回数据
    if(createUser != null) {
      // 生成token
      let token = 'Bearer ' + jwt.sign(
          {name:createUser.user_name, id: createUser.id, superAdmin: true},
          'userToken',
          {expiresIn: '24h'}
      )
      res.send({
        status: 200,
        msg: "登录成功",
        data: createUser
      });
    }



  }
}